package com.local.thread;

import java.util.concurrent.CountDownLatch;
import java.util.concurrent.Executor;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

/**
 * @author relieved-gao
 * @version 1.0 , 2017/11/8
 * @since 1.0
 */
public class TestCountDownLatch {
	public static void main(String[] args) throws InterruptedException {
		new Driver().main();
	}
}

class Driver {
	void main() throws InterruptedException {
		CountDownLatch startSingal = new CountDownLatch(1);
		CountDownLatch doneSingal = new CountDownLatch(3);
		ExecutorService threadPool = Executors.newFixedThreadPool(3);
		for (int i = 0; i < 3; i++) {
			threadPool.execute(new Worker(startSingal, doneSingal));
			//new Thread(new Worker(startSingal, doneSingal)).start();
		}
		System.out.println(Thread.currentThread().getName() + ": don't let run yet");
		startSingal.countDown();
//		System.out.println(Thread.currentThread().getName() + ": do something else");
		doneSingal.await();
		System.out.println(Thread.currentThread().getName() + ": all thread finished work!");
		threadPool.shutdown();
	}
}

class Worker implements Runnable {
	private final CountDownLatch startSingal;
	private final CountDownLatch doneSingal;

	Worker(CountDownLatch startSingal, CountDownLatch doneSingal) {
		this.startSingal = startSingal;
		this.doneSingal = doneSingal;
	}

	@Override public void run() {
		try {
			startSingal.await();
			doWork();
			doneSingal.countDown();
		} catch (InterruptedException e) {

		}
	}

	void doWork() {
		System.out.println(Thread.currentThread().getName() + ": i'm work!");
	}
}
